package edu.hitsz.data;

import GUI.ScorePanel;

import java.io.*;
import java.util.*;

/**
 * @author CsCN
 */
public class ScoreDataImpl implements ScoreDataDAO {
    private List<ScoreObj> scoreList;
    private final String dataFile;

    public ScoreDataImpl(String rawName) {
        this.dataFile = "./src/data/" + rawName + ".dat";
        try {
            FileInputStream fip = new FileInputStream(dataFile);
            ObjectInputStream ois = new ObjectInputStream(fip);
            scoreList = (List<ScoreObj>) ois.readObject();
        } catch (FileNotFoundException e) {
            scoreList = new ArrayList<>();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<ScoreObj> getAllData() {
        return scoreList;
    }


    @Override
    public void doAdd(ScoreObj score) {
        scoreList.add(score);
        Collections.sort(scoreList);
    }

    @Override
    public void toFile() {
        try {
            FileOutputStream fop = new FileOutputStream(dataFile);
            ObjectOutputStream oos = new ObjectOutputStream(fop);
            oos.writeObject(scoreList);
            oos.close();
            fop.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void deleteByIndex(int index) {
        scoreList.remove(index);
    }

    @Override
    public void printAll() {
        int i = 1;
        for (ScoreObj score : scoreList) {
            System.out.print(i++);
            System.out.print('\t' + score.getUserName() + '\t');
            System.out.print(score.getScore());
            System.out.println('\t' + score.getTime());
        }
    }
}
